//var height = $(document.body).height() - 120;
var height = window.parent.$("#frametd").height() - 120;
$(function() {
    if ($(document.body).width() <= 800)
        $("#headertable").hide();
    //奇偶行上色
    $("table.tablegrid > tbody > tr:odd > td").css("backgroundColor", "#F7F7F7");
    $("table.tablegrid > tbody > tr:even > td").css("backgroundColor", "#ffffff");
    //编辑表格加样式
    $("table.tableedit > tbody > tr>td:odd").addClass("act2");
    $("table.tableedit > tbody > tr>td:even").addClass("act1");
    //日期和颜色选择器
    $(".datepicker").datepicker();
    $(".colorpicker").colorpicker();

    //回到顶部
    $(".gotop").click(function() {
        $('html,body').animate({
            scrollTop: $("table")
        }, 500);
    });
    //快捷键
    $(document).bind('keydown', function(e) {
        e = e || window.event;
        if (e.keyCode == 27) {
            $(window.parent.frames['left']).focus();
            $(window.parent.frames['left'].document).find(".e").fadeIn();
        } else if (e.keyCode == 113) {
            window.parent.search();
        }
    });
    $(document).bind('keypress', function(e) {
        if (e.ctrlKey && e.which == 13 || e.which == 10) {

        } else if (e.shiftKey && e.which == 13 || e.which == 10) {

        } else if (e.shiftKey && e.which == 90) {
            window.parent.search();
        }
    });
    //查找会员
    $(".searchit").live("click", function() {
        var field = $(this).attr("field") != undefined ? $(this).attr("field") : 'nickname';
        $("#headertable").data("keyword", field + ':' + $(this).attr("keyword"));
        searchit(this);
    });
    //框架中点击链接加入到导航中去
    $(".navlink").live("click", function() {
        window.parent.navadd($(this).attr("title"), $(this).attr("href"));
        return false;
    });
    //动态跟随弹出框
    $(".dialog").live("click", function() {
        var obj = $(this).closest("a");
        var title = obj.attr("title") != undefined ? obj.attr("title") : LANG.TITLE;
        var width = obj.attr("width") != undefined ? obj.attr("width") : 610;
        var height = obj.attr("height") != undefined ? obj.attr("height") : 500;
        var follow = obj.attr("follow") != undefined ? (obj.attr("follow") == "this" ? this : obj.attr("follow")) : "";
        $.dialog({
            id: 'dialogit',
            title: title,
            width: width,
            height: height,
            follow: follow,
            type: 'iframe',
            content: obj.attr("href"),
            style: 'no_button',
            btnok: LANG.SUBMIT,
            btncancel: LANG.CANCEL,
        });
        return false;
    });
    $(".help").live("click", function() {
        window.top.$.dialog({
            id: 'helpit',
            title: LANG.HELP,
            width: 610,
            height: 500,
            type: 'iframe',
            fixed: true,
            content: SG.admin.base_url + "common/help/" + $(this).attr("module"),
            style: 'no_button',
            btnok: LANG.SUBMIT,
            btncancel: LANG.CANCEL,
        });
        return false;
    });

    //快捷查找会员
    $('a.search').click(function() {
        $("#headertable").data("keyword", '');
        searchit(this);
        return false;
    });
    //清除缓存
    $('a.cache').click(function() {
        $.ajax({
            url: 'general/cache',
            dataType: 'json',
            success: function(ret) {
                if (ret && ret.code == 1) {
                    SG.admin.success(ret.result);
                } else {
                    SG.admin.error(ret.result);
                }
            }, error: function(ret) {
                SG.admin.error(ret);
            }
        });
        return false;
    });
    //自动完成
    autocomplete();
    //调试信息
    $("#debuginfo").click(function() {
        $("#debugdetail").slideToggle();
    });
    $(".multiselect").multiselect({selectAllText: LANG.JS_MULTISELECT_SELECTALLTEXT, noneSelected: LANG.JS_MULTISELECT_NONESELECTED, oneOrMoreSelected: LANG.JS_MULTISELECT_ONEORMORESELECTED});
    if ($("#flexigrid").size() > 0) {
        //避免在窗口大小改变时出现白边
        $(document.body).css("overflow", "hidden");
        //窗口大小改变事件
        $(window).resize(function() {
            var w = $(this).width();
            var h = $(this).height() - 120;
            $("#flexigrid").flexResize(w, h);
        });
    }
});
var toScrollFrame = function(iframe, mask) {
    //do nothing if not iOS devie 
    if (!navigator.userAgent.match(/iPad|iPhone/i))
        return false;
    var mouseY = 0;
    var mouseX = 0;
    $(iframe).ready(function() {
        $(iframe).contents()[0].body.addEventListener('touchstart', function(e) {
            mouseY = e.targetTouches[0].pageY;
            mouseX = e.targetTouches[0].pageX;
        });

        $(iframe).contents()[0].body.addEventListener('touchmove', function(e) {
            e.preventDefault();
            var box = $(mask);
            box.scrollLeft(box.scrollLeft() + mouseX - e.targetTouches[0].pageX);
            box.scrollTop(box.scrollTop() + mouseY - e.targetTouches[0].pageY);
        });
    });

    return true;
};
function autocomplete() {
    //自动完成插件
    $(".autocomplete").each(function() {
        //如果已经绑定了autocomplete则不再绑定
        if ($(this).data("autocomplete"))
            return true;
        var id = $(this).attr("id");
        var table = $(this).attr("table");
        table = id == "user_id" ? "{pre}account_user" : table;
        table = id == "rewardId" ? "{pre}rewardconfig" : table;
        table = id == "openid" ? "{pre}account" : table;
        var fields = $(this).attr("fields");
        fields = id == "openid" ? "openid,openid" : fields;
        $(this).autocomplete({
            params: {
                fields: fields,
                table: table
            },
            type: 'POST',
            dataType: 'JSON',
            width: $(this).attr("w"),
            lookup: null, //使用本地数据
            serviceUrl: "common/autocomplete", //远程获取数据,
            getParamsExtra: typeof getParamsExtra == 'function' ? getParamsExtra : null, //获取扩展参数
            getFillData: function(suggestion) {//实现填充数据不同的功能
                if (typeof setCompleteCallback == 'function') {
                    setCompleteCallback.call(this, suggestion);
                }
                return suggestion.data;
            },
            formatResult: function(suggestion, current) {//实现自定义列表项内容及格式
                return "<em>" + $.Autocomplete.formatResult(suggestion, current) + "</em><ins>" + suggestion.data + "</ins>"
            }
        });
    });
}
function searchit(follow) {
    $.dialog({
        id: 'searchme',
        title: LANG.SEARCH,
        width: 610,
        height: 500,
        follow: follow,
        type: 'iframe',
        content: 'common/search',
        style: 'no_button',
        btnok: LANG.SUBMIT,
        btncancel: LANG.CANCEL,
    });
}
function flexigridsuccess() {
    $(window).resize();
    initweigh(this);
    //拖动事件触发
    $("#flexigrid tr").each(function() {
        $("td:first", this).drag("start", function(ev, dd) {
            return $('<div class="selection" />')
                    .css('opacity', .65)
                    .appendTo(document.body);
        }).drag(function(ev, dd) {
            $(dd.proxy).css({
                top: Math.min(ev.pageY, dd.startY),
                left: Math.min(ev.pageX, dd.startX),
                height: Math.abs(ev.pageY - dd.startY),
                width: Math.abs(ev.pageX - dd.startX)
            });
        }).drag("end", function(ev, dd) {
            $(dd.proxy).remove();
        });
    });
    $('#flexigrid tr').drop("start", function() {
        toggleSelect(this);
    }).drop(function(ev, dd) {
        toggleSelect(this);
    }).drop("end", function() {
        toggleSelect(this);
    });
    $.drop({
        multi: true
    });
    if ($(".asyncdiv").size() > 0 && $(".asyncareabutton").size() == 0) {
        $(".tDiv2").append("<div class='fbutton fasync'></div>");
        $(".fasync").append($(".asyncdiv")).removeClass("fbutton").addClass("asyncareabutton").find(".asyncdiv").css("visibility", "visible");
    }
    $(".flexigrid .mDiv").live("dblclick", function() {
        SG.admin.refresh();
    });
}
function toggleSelect(obj) {
    var t = $(".itemchk", obj)[0].checked;
    $(".itemchk", obj)[0].checked = !t;
    $(obj).toggleClass("trSelected");
}
//初始化排序化功能
function initweigh(_this) {
    //查找就否需要排序
    SG.init("tools.dragsort", function() {
        $("." + _this.gridClass + " .bDiv table").dragsort({
            itemSelector: 'tr',
            dragSelector: "a.moveit",
            dragEnd: saveWeigh,
            placeHolderTemplate: ""
        });
    });
}
function saveWeigh() {
    //改变的值和改变的ID集合
    var changeid = $("td input.itemchk", this).val();
    var data = $(".bDiv table tr td input.itemchk").map(function() {
        return $(this).val();
    }).get().join(',');
    $.ajax({
        url: SG.admin.base_url + "common/weigh",
        type: 'POST',
        data: {
            ids: data,
            changeid: changeid,
            table: SG.admin.table,
            orderway: $("#flexigrid").GetOptions().sortorder
        },
        dataType: 'json',
        success: function(ret) {
            if (ret.code == 1) {
                //SG.admin.refresh();
            }
        },
        error: function(ret) {
            SG.admin.failure(ret, null, true);
        }
    });
}
;

//////////////////////////////////////////////////后台SG.admin对象/////////////////////////////////////////////////
SG.admin = {
    confirm: function(content, type, okcallback, cancelcallback, closecallback, follow) {
        follow = follow != undefined ? follow : false;
        type = type != undefined ? type : 'confirm';
        $.dialog({
            id: 'confirmid',
            title: LANG.WARMTIPS,
            content: "<table class='dialog_table' style='margin:0 auto;'><tr><td><img src='" + SG.config.res_url + "/images/tips/s" + type + ".gif' class='dialog_img_s' /></td><td>" + content + "</td></tr></table>",
            height: 120,
            width: 200,
            fixed: false,
            remove: true,
            lock: false,
            follow: follow,
            style: '',
            btnok: LANG.SUBMIT,
            btncancel: LANG.CANCEL,
            ok: okcallback,
            cancel: cancelcallback,
            close: closecallback
        });
    },
    alert: function(content, type, callback, follow) {
        follow = follow != undefined ? follow : false;
        type = type != undefined ? type : 'help';
        dialog.show({
            id: 'alertid',
            title: LANG.WARMTIPS,
            content: "<table class='dialog_table' style='margin:0 auto;'><tr><td><img src='" + SG.config.res_url + "/images/tips/s" + type + ".gif' class='dialog_img_s' /></td><td>" + content + "</td></tr></table>",
            fixed: true,
            time: 5000,
            height: 120,
            width: 200,
            follow: follow,
            remove: true,
            style: 'no_button',
            btnok: LANG.SUBMIT,
            btncancel: LANG.CANCEL,
            close: callback
        });
    },
    //移除提示窗口
    removetips: function() {
        var tipspanel = $(".tipspanel");
        if (tipspanel.length > 0)
            tipspanel.fadeOut();
    },
    //提示窗口
    tips: function(msg, type, autoclose, timeout, position) {
        type = type ? type : 'normal'
        var tipsname = "tipspanel_" + type;
        var tipspanel = $("#" + tipsname);
        if (tipspanel.length == 0) {
            SG.admin.removetips();
            tipspanel = $("<div id=\"" + tipsname + "\" class=\"tipspanel tips_" + type + "\"/>").appendTo("body");
        }
        if (tipspanel.css("display") != "none") {
            tipspanel.find(">dt").append("<dl>" + msg + "</dl>");
            if (tipstimerid) {
                window.clearTimeout(tipstimerid);
            }
        } else {
            tipspanel.html("<dt><dl>" + msg + "</dl></dt>");
            if (!position) {
                var left = ($(document.body).width() - tipspanel.width()) / 2;
                position = {
                    right: left,
                    top: 9
                };
            }
            tipspanel.css(position).fadeIn();
        }
        if (autoclose) {
            tipstimerid = setTimeout(SG.admin.removetips, timeout);
        }
    },
    //操作成功(内容,位置,是否刷新grid,刷新后的回调)
    success: function(msg, position, refresh, callback) {
        SG.admin.tips(msg, 'success', 1, 5000, position);
        if (refresh)
            SG.admin.refresh(refresh, callback);
    },
    //操作失败
    failure: function(msg, position, refresh, callback) {
        SG.admin.tips(msg, 'failure', 1, 5000, position);
        if (refresh)
            SG.admin.refresh(refresh, callback);
    },
    error: function(msg, position, refresh, callback) {
        SG.admin.tips(msg, 'failure', 1, 5000, position);
        if (refresh)
            SG.admin.refresh(refresh, callback);
    },
    //加载中
    loading: function(msg, position) {
        SG.admin.tips(msg, 'loading', 0, 0, position);
    },
    //刷新数据
    refresh: function(id, callback) {
        id = id != undefined ? id : "#flexigrid";
        id = id == "1" ? "#flexigrid" : id;
        $(id).flexReload({
            onSuccess: callback
        });
    }
}

////////////////////////////////////////////////////////flexigrid function begin/////////////////////////////////////////////////////////
//单个编辑
$(".editit").live("click", function() {
    $.dialog({
        id: 'edit',
        title: LANG.EDIT,
        width: 635,
        height: 495,
        type: 'iframe',
        content: SG.admin.edit_url + $(this).attr("rel"),
        style: 'no_button',
        btnok: LANG.SUBMIT,
        btncancel: LANG.CANCEL,
    });
});
//单个回复
$(".replayit").live("click", function() {
    $.dialog({
        id: 'replay',
        title: LANG.REPLAY,
        width: 635,
        height: 495,
        type: 'iframe',
        content: SG.admin.replay_url + $(this).attr("rel"),
        style: 'no_button',
        btnok: LANG.SUBMIT,
        btncancel: LANG.CANCEL,
    });
});
//详情
$(".detailit").live("click", function() {
    $.dialog({
        id: 'detail',
        title: LANG.DETAIL,
        width: 635,
        height: 495,
        type: 'iframe',
        content: SG.admin.detail_url + $(this).attr("rel"),
        style: 'no_button',
        btnok: LANG.SUBMIT,
        btncancel: LANG.CANCEL,
    });
});
//单个删除
$(".delit").live("click", function() {
    var id = $(this).attr("rel");
    $.dialog({
        id: 'confirmid',
        title: LANG.WARMTIPS,
        content: "<table class='dialog_table' style='margin:0 auto;'><tr><td><img src='" + SG.config.res_url + "/images/tips/sask.gif' class='dialog_img_s' /></td><td>" + LANG.JS_TEXT_CONFIRM_DELETE_ONE + "</td></tr></table>",
        height: '120',
        width: 200,
        fixed: false,
        x: $(this).offset().left,
        y: $(this).offset().top,
        remove: true,
        follow: this,
        lock: false,
        style: '',
        btnok: LANG.SUBMIT,
        btncancel: LANG.CANCEL,
        ok: function() {
            $.ajax({
                url: SG.admin.del_url + id,
                type: 'POST',
                data: {
                    areaIds: $(".multiselect").selectedValuesString()
                },
                dataType: 'json',
                success: function(ret) {
                    if (ret.code == 1) {
                        if (ret.result && ret.result.length >= 4 && typeof ret.result == "object") {
                            window.top.async(ret.result[0], ret.result[1], ret.result[2], ret.result[3]);
                        }
                        SG.admin.success(LANG.C_TIPS_SUCCESS_TEXT);
                        SG.admin.refresh();
                    } else {
                        SG.admin.failure(ret.result);
                    }
                },
                error: function(ret) {
                    SG.admin.failure(ret);
                }
            });
        }
    });
});
//点击列中的数据进行筛选
$('.filterit').live('click', function() {
    filterit($(this).attr('field'), $(this).attr('value'), $(this).attr('op'));
    return false;

    //追加到option列表框
    var s = $("select[name=qtype] option[value^='" + $(this).attr('field') + "']");
    if (!s.size()) {
        $("select[name=qtype]").append("<option value='" + $(this).attr('field') + "$=$0' selected='selected'>" + $(".hDiv table thead th[abbr='" + $(this).attr('field') + "']").text() + "</option>");
    } else {
        $("select[name=qtype] option").removeAttr("selected");
        s.attr('selected', 'selected');
    }
    $('.qsbox').val($(this).attr('value'));
    $("input[name=qsubmitbtn]").click();
    SG.bganimation($(".qsbox"), 3000);
});
//添加过滤选项
function filterit(field, value, op, title) {
    var flex = $("#flexigrid").closest(".flexigrid");
    var sd = $(".sDiv", flex);
    if ($("a[name='" + field + "']").size() == 0) {
        title = title != undefined && title != '' ? title : $(".hDiv table thead th[field='" + field + "']", flex).text();
        op = op != undefined && op != '' ? op : '=';
        var app = $("<a href='javascript:;' title='" + LANG.JS_FLEXI_REMOVEFILTER + "' op='" + op + "' name='" + field + "'><b>" + title + " " + op + "</b><u>" + value + "</u><i>×</i></a>");
    } else {
        $("a[name='" + field + "'] u").text(value);
    }
    sd.show();
    $(".sDiv3", sd).append(app);
    $("input[name=qsubmitbtn]", flex).click();
    SG.bganimation(app, 1000, null, '#A8D8EB', false);
}
//批量操作
function multi(name, grid) {
    var ids = $("#flexigrid").getCheckedRows();
    var current = $(".fbutton ." + name);
    if (name == 'delete') {
        if (ids.length == 0)
            return SG.admin.alert(LANG.JS_TEXT_SELECT_LEAST_ONE, "error", {}, current);
        SG.admin.confirm(LANG.JS_TEXT_CONFIRM_DELETE_MULTI.replace(/{nums}/, ids.length), 'ask', function() {
            _multi(name, ids);
        }, {}, {}, current);
    } else if (name == 'reject') {
        if (ids.length == 0)
            return SG.admin.alert(LANG.JS_TEXT_SELECT_LEAST_ONE, "error", {}, current);
        _multi(name, ids);
    } else if (name == 'accept') {
        if (ids.length == 0)
            return SG.admin.alert(LANG.JS_TEXT_SELECT_LEAST_ONE, "error", {}, current);
        _multi(name, ids);
    } else if (name == 'export') {
        if (ids.length == 0)
            return SG.admin.alert(LANG.JS_TEXT_SELECT_LEAST_ONE, "error", {}, current);
        //_multi(name, ids);
        $("#flexigrid").exportCSV();
    } else if (name == 'add') {
        $.dialog({
            id: 'add',
            title: LANG.ADD,
            width: 635,
            height: 495,
            type: 'iframe',
            content: SG.admin.add_url,
            style: 'no_button',
            btnok: LANG.SUBMIT,
            btncancel: LANG.CANCEL,
        });
    } else {
        _multi(name, ids);
    }
}
//批量操作
function _multi(type, ids) {
    $.ajax({
        url: SG.admin.multi_url,
        type: 'post',
        dataType: 'json',
        data: {
            type: type,
            ids: ids.join(','),
            areaIds: $(".multiselect").selectedValuesString()
        },
        success: function(ret) {
            if (ret.code != undefined) {
                if (ret.code == 1) {
                    SG.admin.success(LANG.C_TIPS_SUCCESS_TEXT);
                    SG.admin.refresh();
                    if (ret.result.length >= 4 && typeof ret.result == "object") {
                        window.top.async(ret.result[0], ret.result[1], ret.result[2], ret.result[3]);
                    }
                } else {
                    SG.admin.error(ret.result);
                }
            }
        },
        error: function(ret) {
            SG.admin.error(ret.result);
        }
    });
}
//flexigrid操作
function formatOp(text, id, cell) {
    var a = [];
    //是否需要移动排序
    if ($("#flexigrid").GetOptions().cols.indexOf(".weigh,") != -1 || $("#flexigrid").GetOptions().cols.indexOf(",weigh,") != -1)
    {
        a.push("<a class='moveit' href='javascript:;' rel='" + id + "'><span class='smove' title='" + LANG.SORT + "'>" + LANG.SORT + "</span></a>&nbsp;");
    }
    if (SG.admin.edit_url)
    {
        a.push("<a class='editit' href='javascript:;' rel='" + id + "'><span class='sedit' title='" + LANG.EDIT + "'>" + LANG.EDIT + "</span></a>&nbsp;");
    }
    if (SG.admin.replay_url)
    {
        a.push("<a class='replayit' href='javascript:;' rel='" + id + "'><span class='sreplay' title='" + LANG.MAINTAIN + "'>" + LANG.MAINTAIN + "</span></a>&nbsp;");
    }
    if (SG.admin.del_url)
    {
        a.push("<a class='delit' href='javascript:;' rel='" + id + "'><span class='sdelete' title='" + LANG.DEL + "'>" + LANG.DEL + "</span></a>&nbsp;");
    }
    if (SG.admin.detail_url)
    {
        a.push("<a class='detailit' href='javascript:;' rel='" + id + "'><span class='sreplay' title='" + LANG.DETAIL + "'>" + LANG.DETAIL + "</span></a>&nbsp;");
    }
    return a.join("");
}
//查找
function formatSearch(text, id, cell, field) {
    return "<a href=\"javascript:;\" class='filterit' field='" + field + "' value='" +
            (text === '' || text == '&nbsp;' ? 'null' : text) + "'>" +
            (text === '' || text == '&nbsp;' ? '<font color=gray>null</font>' : text) + "</a>" +
            (field.indexOf('nickname') != -1 ? " <img src='" + SG.config.res_url + "/images/icons/sfind.png' class='searchit' keyword='" + text + "' />" : '');
}
//状态
function formatState(value, id, cell, field) {
    var arr = [{
            color: 'green',
            text: LANG.NORMAL,
            value: 1
        }, {
            color: 'gray',
            text: LANG.DISABLED,
            value: 0
        }];
    return filterGeneral(arr, value, field);
}
function formatImage(value) {
    return "<img src='" + SG.config.res_url + value + "' width='25' height='25' />";
}
function formatPercent(value) {
    return value + "%";
}
function formatSex(value, id, cell, field) {
    var typearr = {
        '0': '<font color=green>' + LANG.FEMALE + '</font>',
        '1': '<font color=blue>' + LANG.MALE + '</font>'
    };
    var arr = [];
    $.each(typearr, function(i, j) {
        arr.push({
            color: '',
            text: j,
            value: i
        });
    });
    return filterGeneral(arr, value, field);
}
function filterGeneral(arr, value, field) {
    var t = value;
    $(arr).each(function() {
        if (value == this.value) {
            t = "<font color='" + this.color + "'>" + this.text + "</font>";
            return false;
        }
    });
    return "<a href=\"javascript:;\" class='filterit' field='" + field + "' value='" + value + "'>" + t + "</a>";
}
//点击事件
function clickhandler(row) {
    //双击事件
    $(row).dblclick(function() {
        $(".sedit", row).click();
    });
}
//闪烁Flexigrid中的指定行
function row_flash(id) {
    setTimeout(function() {
        SG.bganimation($("#row" + id + " td"), 3000, "#ffffff");
    }, 500);
}

function binddate() {
    $(".datepicker").datepicker();
    $(".datepicker").live("change", function() {
        if ($(this).val()) {
            filterit($(this).attr("name"), $(this).val(), $(this).attr("op"), LANG.DATE);
        }
    });
    if (SG.flexOptions.searchbar == 1) {
        $("#" + this.id + " .pSearch").click();
    }
}
////////////////////////////////////////////////////////flexigrid function end/////////////////////////////////////////////////////////